/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.employee.service;

import java.util.Date;
import java.util.List;

import com.thinkgem.jeesite.modules.employee.dao.StatutoryHolidaysDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.CalendarUtils;
import com.thinkgem.jeesite.common.utils.Constons;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.costs.dao.WarehouseLaborCostsDao;
import com.thinkgem.jeesite.modules.costs.entity.WarehouseLaborCosts;
import com.thinkgem.jeesite.modules.employee.dao.EmployeeLeaveDao;
import com.thinkgem.jeesite.modules.employee.dao.OutsourceCostDetailDao;
import com.thinkgem.jeesite.modules.employee.entity.AttendanceRecords;
import com.thinkgem.jeesite.modules.employee.entity.CountOutsourceCost;
import com.thinkgem.jeesite.modules.employee.entity.Employee;
import com.thinkgem.jeesite.modules.employee.entity.EmployeeLeave;
import com.thinkgem.jeesite.modules.employee.entity.LogisticsCost;
import com.thinkgem.jeesite.modules.employee.entity.OutsourceCostDetail;
import com.thinkgem.jeesite.modules.employee.entity.SummaryAttendance;
import com.thinkgem.jeesite.modules.sys.entity.User;

/**
 * 外包工考勤成本明细表Service
 * @author pan.zhou
 * @version 2017-07-26
 */
@Service
@Transactional(readOnly = true)
public class OutsourceCostDetailService extends CrudService<OutsourceCostDetailDao, OutsourceCostDetail> {
    
    @Autowired
    protected OutsourceCostDetailDao dao;
    @Autowired
	private AttendanceRecordsService attendanceRecordsService;
	@Autowired
    private EmployeeService employeeService;
	@Autowired
	private EmployeeLeaveService employeeLeaveService;
	@Autowired
	private WarehouseLaborCostsDao  warehouseLaborCostsDao;
	@Autowired
	private EmployeeLeaveDao employeeLeaveDao;
	@Autowired
	private StatutoryHolidaysDao statutoryHolidaysDao;
/*	@Autowired
	private CountOutsourceCost summaryAttendance;*/

	public OutsourceCostDetail get(String id) {
		return super.get(id);
	}
	
	public List<OutsourceCostDetail> findList(OutsourceCostDetail outsourceCostDetail) {
		return super.findList(outsourceCostDetail);
	}
	
	public Page<OutsourceCostDetail> findPage(Page<OutsourceCostDetail> page, OutsourceCostDetail outsourceCostDetail) {
		return super.findPage(page, outsourceCostDetail);
	}
	
	@Transactional(readOnly = false)
	public void save(OutsourceCostDetail outsourceCostDetail) {
		super.save(outsourceCostDetail);
	}
	
	@Transactional(readOnly = false)
	public void delete(OutsourceCostDetail outsourceCostDetail) {
		super.delete(outsourceCostDetail);
	}

    public Page<CountOutsourceCost> queryCountOutsourcePage(Page<CountOutsourceCost> page,
                                                            CountOutsourceCost outsourceCostDetail) {
        outsourceCostDetail.setPage(page);
        page.setList(dao.queryCountOutsourcePage(outsourceCostDetail));
        return page;
    }

	/**
	 * 统计生成每天仓库运营成本
	 * @param date
	 */
	@Transactional(readOnly = false)
	public void genToDayOutsourceCostDetail(Date date) {
		String isOldUser =Constons.N;
		int week =  CalendarUtils.getWeek(date);
		Date monday = CalendarUtils.diffDate(date, week-1);
		//先获取所有考勤里面是外包工的数据
		List<AttendanceRecords> attendanceRecordsList = attendanceRecordsService.queryAllByOutSourceEmloee(date, Constons.WarehouseType.UKLE,Constons.UserType.Outsourcing.getTypeCode());
		for(AttendanceRecords one: attendanceRecordsList){
			//查询用户
			Employee employee =  employeeService.findOneByEmployeeNumer(one.getEmployeenumber());
			//查询某个用户在一段时间内的总工时
			double totalWeek = attendanceRecordsService.queryTotalWeekByOutSourceEmloeeAndWeek(monday,date,one.getEmployeenumber());
			//判断用户是否入职12周
			Date entryDate =employee.getEntryDate();
			if(CalendarUtils.greaterThanOrEqualDate(date,entryDate)){
				isOldUser =Constons.Y;
			}

			//查询本周内修的年假
			double holiday =  employeeLeaveService.queryEmployeeLeaveByUserAndDays(employee.getNumber(),monday,date,Constons.HolidayType.Annual_leave.getTypeCode());
			//如果是判断是否加班超过40个小时
			double jiabanTime = totalWeek+holiday-40;
			jiabanTime = (jiabanTime>0&&isOldUser.equals(Constons.Y))?jiabanTime:0;
			double todayWork = Double.valueOf(one.getWorkHour());
			if(jiabanTime>todayWork){
				jiabanTime = todayWork;
			}
			OutsourceCostDetail outsourceCostDetail = new OutsourceCostDetail(employee.getNumber(),date);
			//查询是否统计过
			OutsourceCostDetail dbCostDetail = dao.getByEntity(outsourceCostDetail);
			if(null!=dbCostDetail&& StringUtils.isNotEmpty(dbCostDetail.getId())){
				outsourceCostDetail.setId(dbCostDetail.getId());
				outsourceCostDetail.preUpdate();
			}
			outsourceCostDetail.setCompany(employee.getCompany());

			outsourceCostDetail.setOffice(employee.getOffice());
			outsourceCostDetail.setWageStandard(employee.getHourlyStandard());
			outsourceCostDetail.setWageHour(String.valueOf(totalWeek));
			outsourceCostDetail.setNormalHour((Double.valueOf(one.getWorkHour())>=8.0)?"8":one.getWorkHour());
			outsourceCostDetail.setOvertimeHour(String.valueOf(jiabanTime));
			double normalNoney = Double.valueOf(outsourceCostDetail.getWageStandard())*Double.valueOf(outsourceCostDetail.getNormalHour());
			outsourceCostDetail.setNormalMoney(String.valueOf(normalNoney));
			double overTimeMoney =Double.valueOf(outsourceCostDetail.getWageStandard())*Double.valueOf(outsourceCostDetail.getOvertimeHour())*1.5;
			outsourceCostDetail.setOvertimeMoney(String.valueOf(overTimeMoney));
			outsourceCostDetail.setDiffAdjust("0");
			double totalMoney = normalNoney+overTimeMoney;
			outsourceCostDetail.setTemporaryMoney(String.valueOf(totalMoney));
			outsourceCostDetail.setAddedTax("0.19");
			double outsourcingMoney = totalMoney*(1+0.19);
			outsourceCostDetail.setOutsourcingMoney(String.valueOf(outsourcingMoney));
			WarehouseLaborCosts laborCosts = warehouseLaborCostsDao.getRate(Constons.CountryWarehouse.UK_Warehouse.getTypeCode());
			if(laborCosts!=null){
			    outsourceCostDetail.setExchangeRate(laborCosts.getExchangeRate());
			}			
			double total = outsourcingMoney*Double.valueOf(outsourceCostDetail.getExchangeRate());
			outsourceCostDetail.setTotalMoney(String.valueOf(total));
			
			
			User user = new User();
			user.setId("1");

			outsourceCostDetail.setCreateBy(user);
			outsourceCostDetail.setUpdateBy(user);
			outsourceCostDetail.setCreateDate(new Date());
			outsourceCostDetail.setUpdateDate(new Date());
			super.save(outsourceCostDetail);
		}

	}
	/**
	 * 
	 * 查询间接物流成本列表
	 * @param page
	 * @param logisticsCost
	 * @return
	 */
    public Page<LogisticsCost> queryLogisticsCostPage(Page<LogisticsCost> page, LogisticsCost logisticsCost) {
        logisticsCost.setPage(page);
        page.setList(dao.queryLogisticsCostPage(logisticsCost));
        return page;
    }

    public Page<SummaryAttendance> querySummaryAttendancePage(Page<SummaryAttendance> page,
                                                              SummaryAttendance summaryAttendance) {
        summaryAttendance.setPage(page);
        page.setList(dao.querySummaryAttendancePage(summaryAttendance));
		List<SummaryAttendance> list = page.getList();
		page.setList(setHoliday(list,summaryAttendance.getStartDate(),summaryAttendance.getEndDate()));
        return page;
    }

	/**
	 * 查询仓库某时段考勤汇总
	 * @param name
	 * @param startday
	 * @param endDay
	 * @return
	 */
	public List<SummaryAttendance> querySummaryAttendanceByList(String name, Date startday, Date endDay) {
		List<SummaryAttendance> list = dao.querySummaryAttendanceList(name,startday,endDay);
		return setHoliday(list,startday,endDay);
	}
    private List<SummaryAttendance> setHoliday(List<SummaryAttendance> list,Date start,Date end){

		for (SummaryAttendance summary : list) {

				double holiday = statutoryHolidaysDao.countByDate(start,end);
				summary.setHoliday(holiday);
				//处理年假
				int  annualLeaveDay =  dealHoliday(summary, Constons.HolidayType.Annual_leave.getTypeCode());
				summary.setAnnualLeave(annualLeaveDay);
				//病假
				int stickLeaveDay = dealHoliday(summary, Constons.HolidayType.Stick_Leave.getTypeCode());
				summary.setStickLeave(stickLeaveDay);
				//事假
				int compassionateLeaveDay = dealHoliday(summary, Constons.HolidayType.Compassionate_Leave.getTypeCode());
				summary.setStickLeave(compassionateLeaveDay);
				//陪产假
				int paternityLeaveDay = dealHoliday(summary, Constons.HolidayType.Paternity_leave.getTypeCode());
				summary.setStickLeave(paternityLeaveDay);
				//婚假
				int marriageHolidayDay = dealHoliday(summary, Constons.HolidayType.Marriage_holiday.getTypeCode());
				summary.setMarriageHoliday(marriageHolidayDay);
				//产检假
				int antenatalLeaveDay = dealHoliday(summary, Constons.HolidayType.Marriage_holiday.getTypeCode());
				summary.setAnnualLeave(antenatalLeaveDay);
				//丧假
				int funeralLeaveDay = dealHoliday(summary, Constons.HolidayType.Funeral_leave.getTypeCode());
				summary.setFuneralLeaveDay(funeralLeaveDay);
				//调休
				int paidLeaveDay = dealHoliday(summary, Constons.HolidayType.Paid_leave.getTypeCode());
				summary.setPaidLeaveDay(paidLeaveDay);
				//其它假期
				int otherLeaveDay = dealHoliday(summary, Constons.HolidayType.Other_leave.getTypeCode());
				summary.setOtherLeaveDay(otherLeaveDay);


		}
		return list;
	}
	private int dealHoliday(SummaryAttendance summary,String type){
		int total = 0;
		Date queryStartDate = summary.getStartDate();
		Date queryEndDate = summary.getStartDate();
		//查询假期
		List<EmployeeLeave> employeeLeaves = employeeLeaveDao.queryByUserAndDate(summary.getEmployeeNumber(), type, summary.getStartDate(), summary.getEndDate());
		if(employeeLeaves!=null&&employeeLeaves.size()>0){
			for (EmployeeLeave employeeLeave : employeeLeaves) {
				Date startDate = employeeLeave.getStartTime();
				Date endDate = employeeLeave.getEndTime();

				Date satartDate_flag = employeeLeave.getStartTime();
				Date endDate_flag = employeeLeave.getEndTime();

				if(CalendarUtils.compare(queryStartDate,startDate)){
					satartDate_flag = queryStartDate;
				}
				if(CalendarUtils.compare(endDate,queryEndDate)){
					endDate_flag = queryEndDate;
				}

				//计算天数
				int days = CalendarUtils.diffDate(satartDate_flag,endDate_flag)+1;
				int hours = days*8;
				if(StringUtils.isNotBlank(employeeLeave.getLeaveTime())&&Integer.valueOf(employeeLeave.getLeaveTime())<hours){
					total = total+Integer.valueOf(employeeLeave.getLeaveTime());
				}else{
					total = total+hours;
				}
			}
		}
		return total;
	}


}